#!/usr/bin/env python
# -*- coding: utf-8 -*-
#r
#       untitled.py
#
#       Copyright 2008 Mirat Can Bayrak <horselogy@pardus-nx8220>
#

import pygtk , sys
try:
    pygtk.require('2.0')
except:
    print "Sorry you need greater version of pygtk (min: 2.0)"
import gtk , gtk.glade , urllib , re , gtkdllib
from video_service import video_service
from urlparse import urlparse
#--------------------------------------------------------------------------------------------------#
class video_grabber:
    def __init__(self):
        self.wtree         = gtk.glade.XML('gui/main.glade')
        self.window        = self.wtree.get_widget('window1')
        self.enter_url     = self.wtree.get_widget('entry1')
        self.progress_bar  = self.wtree.get_widget('progressbar1')
        self.folder_select = self.wtree.get_widget('filechooserbutton1')
        self.info_line     = self.wtree.get_widget('label5')
        self.button        = self.wtree.get_widget('button1')
        signals            = {'end_program'   : self.end_program ,'show_svc': self.show_svc}
        self.wtree.signal_autoconnect(signals)
        self.button.set_label('gtk-save')
        self.button_handler = self.button.connect('clicked',self.start)
        self.window.show()
    def show_svc(self,widget=None,data=None):
        dummy = video_service(None)
        temp = str()
        print dummy.identified_domains
        for service in dummy.identified_domains:
            print service
            temp = temp + service + '\n'
        self.show_msg(msg=temp)
        del(dummy)
    def info(self,msg):
        self.info_line.set_text(msg)
        while gtk.events_pending(): gtk.main_iteration()
        print msg
    def start(self,widget=None,data=None):
        print "start called"
        self.info("fetching data about page")        
        self.service = video_service(self.enter_url.get_text())
        if self.service.identify():
            self.button.set_sensitive(False)
            self.info("video service identified (%s)" % self.service.domain)
            data = self.service.fetch()
            if data: # fetched correctly
                self.button.set_label("gtk-stop")
                self.button.disconnect(self.button_handler)
                self.button_handler = self.button.connect("clicked",self.stop)
                self.button.set_sensitive(True)
                video_source,video_name = data[1], data[0]
                save_folder = self.folder_select.get_filename()
                self.info("Fetched video source : " + video_source)
                self.info("Downloading : " + video_name)
                fname = video_name.replace(" " , "_") + ".flv"
                self.downloader = gtkdllib.downloader(video_source,save_folder,fname,self.progress_bar,'in_kb')
                self.downloader.start()
            else:
                
                self.info("There was error when cropping data from page")
                msg = """
Error accured when fetching data fr4om web page
Please don't try to be cute and report that error with following lines:

Domain : %s
Full Url: %s
File Grabber Regexp : %s
File Crop : %s
Name Grabber Regexp : %s 
Name Crop : %s""" % (self.service.domain ,
                     self.service.url,
                     self.service.regs[self.service.domain]['file_grabber'],
                     str(self.service.regs[self.service.domain]['file_crop']),
                     self.service.regs[self.service.domain]['name_grabber'],
                     str(self.service.regs[self.service.domain]['name_crop']),
                    )
                self.show_msg(msg = msg)
                self.button.set_sensitive(True)
        else:
            self.show_msg(msg = "The url that you have entered is invalid or not supported video service.")
            self.info("invalid url entered")
    def stop(self,widget=None,data=None):
        print "stop called"
        self.downloader.stop()
        self.button.disconnect(self.button_handler)
        self.button_handler = self.button.connect('clicked',self.start)
        self.button.set_label("gtk-save")
    def show_msg(self, widget =None, data =None, msg = ""):
        """
        * Sadece dialog açar , mesajı gösterir, tamama basınca kapatır.
        """
        dialog = gtk.MessageDialog(
                None,
                gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
                gtk.MESSAGE_INFO, gtk.BUTTONS_OK,
                str(msg))
        dialog.run()
        dialog.destroy()
    def end_program(self,widget,data=None):
        if self.button.get_label() == "gtk-stop":
            self.info("Stopping download before closing.")
            self.stop()
        self.info("Bye")
        gtk.main_quit()
def main():
    program = video_grabber()
    gtk.main()
    return 0
if __name__ == '__main__': main()
